import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/site/site_device_list/site_device_list_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';

class AccessDeviceByScannerController extends GetxController {
  final count = 0.obs;
  List<String> titleList = [];
  List<String> detailList = [];
  final DeviceServices services = Get.put(DeviceServices());
  SiteDeviceListController controller = Get.find();
  DeviceListModel model = DeviceListModel();
  late int siteId;

  @override
  void onInit() {
    super.onInit();
    titleList = [
      ResKey.siteDeviceAccessOwningUnit.tr,
      ResKey.siteDeviceAccessProductType.tr,
      ResKey.siteDeviceAccessProductModel.tr,
      ResKey.deviceName.tr,
      ResKey.deviceSn.tr,
    ];
    if (Get.arguments != null) {
      if (Get.arguments['device'] != null) {
        model = Get.arguments['device'];
      }
      if (Get.arguments['siteId'] != null) {
        siteId = Get.arguments['siteId'];
      }
      detailList = [
        model.subsystemName != null?model.subsystemName.toString():'',
        model.productTypeName != null?model.productTypeName.toString():'',
        model.model != null?model.model.toString():'',
        model.name != null?model.name.toString():'',
        model.sn != null?model.sn.toString():'',
      ];
    }
  }

  ///设备图片列表
  List<String> deviceImageList = [];

  @override
  void onReady() {}

  @override
  void onClose() {}

  Future<void> complete() async {
    var param = {
      'siteId': siteId ?? 1,
      'deviceId': model.deviceId ?? '',
      'photos': deviceImageList.join(',')
    };
    if (deviceImageList.isNotEmpty) {
      param['photos'] = deviceImageList.join(',');
    }

    var result = await services.postSnDeviceAccess(param, onError: (error) {
      handleException(error);
      return false;
    });
    if (result != null) {
      Log.d('result==' + result.toString());
      _goBackToDeviceListPage();
    }
  }

  ///返回到设备列表页
  _goBackToDeviceListPage() {
    controller.refreshData();
    Get.until((route) => route.settings.name == RouterPath.siteDeviceList);
  }
}
